<template>
    <div class="live-room-management">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-row :gutter="20" style="display:flex;align-items:center;justify-content:space-between;">
                <div style="display:flex;align-items:center;">
                    <el-col :span="8">
                        <p>手机号</p>
                        <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
                    </el-col>

                    <el-col :span="8" v-if="activeTab !== 'replay'">
                        <p>{{ activeTab !== 'live' ? '审核状态' : '直播状态' }}</p>
                        <el-select v-if="activeTab !== 'live'" v-model="searchForm.auditStatus" placeholder="全部"
                            clearable>
                            <el-option label="全部" value="" />
                            <el-option label="待审核" value="0" />
                            <el-option label="已通过" value="1" />
                            <el-option label="已拒绝" value="2" />
                        </el-select>

                        <el-select v-else v-model="searchForm.liveStatus" placeholder="全部" clearable>
                            <el-option label="全部" value="" />
                            <el-option label="正常" value="normal" />
                            <el-option label="异常" value="abnormal" />
                        </el-select>
                    </el-col>

                    <el-col :span="8">
                        <p>用户ID</p>
                        <el-input v-model="searchForm.id" placeholder="请输入用户ID" clearable />
                    </el-col>
                </div>

                <el-col :span="6">
                    <p>&nbsp;</p>
                    <el-input v-model="searchForm.keyword" placeholder="请输入用户名/直播间标题" clearable
                        @keyup.enter="handleSearch">
                        <template #append>
                            <el-button @click="handleSearch">搜索</el-button>
                        </template>
                    </el-input>
                </el-col>
            </el-row>
        </div>

        <div class="center">
            <!-- 标签页 -->
            <div class="tab-area">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="预告" name="preview" />
                    <el-tab-pane label="直播" name="live" />
                    <el-tab-pane label="回放" name="replay" />
                </el-tabs>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <el-table :data="tableData" style="width:100%" border stripe
                    :header-cell-style="{ background: '#f5f7fa' }">
                    <el-table-column prop="id" label="用户ID" min-width="120" />
                    <el-table-column label="头像" width="70">
                        <template #default="scope">
                            <el-avatar :src="scope.row.avatar" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="用户名" min-width="120" />
                    <el-table-column prop="phone" label="手机号" min-width="120" />
                    <el-table-column prop="title" label="直播间标题" min-width="240">
                        <template #default="scope">
                            <el-tooltip effect="dark" :content="scope.row.title" placement="top">
                                <div class="title-ellipsis">{{ scope.row.title }}</div>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="startTime" label="开播时间" min-width="160" />

                    <!-- 审核状态 -->
                    <el-table-column v-if="activeTab === 'preview'" label="审核状态" min-width="120">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <!-- 直播状态 -->
                    <el-table-column v-if="activeTab === 'live'" label="直播状态" min-width="120">
                        <template #default="scope">
                            <el-tag :type="getLiveStatusType(scope.row.liveStatus)">
                                {{ getLiveStatusText(scope.row.liveStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="180" fixed="right">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="handleView(scope.row)">
                                查看
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination v-model:currentPage="pagination.currentPage" v-model:page-size="pagination.pageSize"
                        :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" background />
                </div>
            </div>
        </div>

        <!-- 抽屉/弹窗 -->
        <LivepreviewDetail v-model:visible="Livepreviewdrawer" :row-data="currentRowData"
            @audit-success="onAuditSuccess" />
        <VodpreviewDetail v-model:visible="vodpreviewdrawer" :row-data="currentRowData" />
        <LiveorplaybackDetail v-model:visible="Liveorplaybackdrawer" :row-data="currentRowData" />
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { list } from '@/api/live'
import LivepreviewDetail from './livepreviewDetail.vue'
import VodpreviewDetail from './vodpreviewDetail.vue'
import LiveorplaybackDetail from './liveorplaybackDetail.vue'


// 审核状态 tag 颜色
const getStatusType = (status) => {
    switch (status) {
        case '0': return 'warning'
        case '1': return 'primary'
        case '2': return 'danger'
        default: return 'info'
    }
}

const getStatusText = (status) => {
    switch (status) {
        case '0': return '待审核'
        case '1': return '已通过'
        case '2': return '已驳回'
        default: return '-'
    }
}

// 直播状态 tag 颜色
const getLiveStatusType = (status) => {
    switch (status) {
        case 'normal': return 'success'
        case 'abnormal': return 'danger'
        default: return 'info'
    }
}

const getLiveStatusText = (status) => {
    switch (status) {
        case 'normal': return '正常'
        case 'abnormal': return '异常'
        default: return '-'
    }
}

// 审核成功后局部更新
function onAuditSuccess({ id, status }) {
    console.log('receive audit-success', id, status)
    const target = tableData.value.find(item => item.id === id)
    if (target) {
        target.status = status
        console.log('updated row status =', target.status)
    }
}
// 搜索表单 
const searchForm = reactive({
    phone: '',
    auditStatus: '',
    liveStatus: '',
    userId: '',
    keyword: ''
})

//  标签页 
const activeTab = ref('preview')

//  抽屉 
const Livepreviewdrawer = ref(false)
const vodpreviewdrawer = ref(false)
const Liveorplaybackdrawer = ref(false)
const currentRowData = ref({})

//  分页 
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

//  表格数据 
const tableData = ref([])

//  拉取数据 
const fetchData = async () => {
    try {
        const params = {
            userId: searchForm.userId ? Number(searchForm.userId) : undefined,
            livestreamStatus:
                activeTab.value === 'live'
                    ? searchForm.liveStatus === 'normal'
                        ? 1
                        : searchForm.liveStatus === 'abnormal'
                            ? 2
                            : undefined
                    : undefined,
            pageNum: pagination.currentPage - 1,
            pageSize: pagination.pageSize
        };

        const res = await list(params);
        const { records = [], totalCount = 0 } = res.data || {};

        tableData.value = records.map(r => ({
            id: r.id,
            userId: String(r.userId ?? ''),
            username: r.userName,
            phone: r.userTel,
            title: r.livestreamTitle ?? '',
            startTime: r.livestreamStartTime
                ? new Date(r.livestreamStartTime).toLocaleString()
                : '',
            status: String(r.reviewStatus ?? ''),
            liveStatus: r.liveStatus === 1 ? 'normal' : 'abnormal',
            avatar: r.reservationCover ?? '',
            type: activeTab.value === 'preview' ? 'Livepreview' : 'Liveorplayback'
        }));
        console.log('records:', res.data.records)
        pagination.total = totalCount;

    } catch (e) {
        console.error(e);
    }
};

//  搜索 & 分页事件 
const handleSearch = () => {
    pagination.currentPage = 1
    fetchData()
}
const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchData()
}
const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchData()
}

//  查看详情 */
const handleView = (row) => {
    const detail = tableData.value.find(item => item.id === row.id)
    if (detail) {
        currentRowData.value = detail
        if (detail.type === 'Livepreview') {
            Livepreviewdrawer.value = true
        } else if (detail.type === 'vodpreview') {
            vodpreviewdrawer.value = true
        } else {
            Liveorplaybackdrawer.value = true
        }
    } else {
        ElMessage.error('未找到对应详情')
    }
}

//  监听变化 
watch([activeTab, () => pagination.currentPage, () => pagination.pageSize, searchForm], fetchData, { deep: true })
watch(activeTab, () => {
    // 切标签时重置分页
    pagination.currentPage = 1
    searchForm.auditStatus = ''
    searchForm.liveStatus = ''
})

//  首次加载 
fetchData()
</script>


<style scoped>
.live-room-management {
    box-sizing: border-box;
    width: 100%;
    background-color: rgb(248, 248, 248);
}

.search-area {
    padding: 10px 20px;
    background-color: white;
    border-radius: 10px;
    margin-bottom: 20px;
}

.center {
    padding: 10px 20px;
    background-color: white;
    border-radius: 10px;
    margin-top: 10px;
}

.tab-area {
    margin-bottom: 20px;
}

.title-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20px;
}

.custom-pagination {
    --el-pagination-hover-bg-color: #f5f7fa;
    --el-pagination-bg-color: transparent;
    --el-pagination-text-color: #606266;
    --el-pagination-button-disabled-bg-color: #f5f7fa;
    --el-pagination-button-disabled-text-color: #c0c4cc;
}

.pagination-pages {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
}

.pagination-btn {
    min-width: 32px;
    height: 32px;
    padding: 0;
    margin: 0 4px;
    background-color: transparent;
    border: 1px solid #dcdfe6;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pagination-btn:hover {
    color: #409eff;
}

.pagination-btn.active {
    background-color: #409eff;
    color: #fff;
    border-color: #409eff;
}

.pagination-btn.disabled {
    color: #c0c4cc;
    cursor: not-allowed;
}

.ellipsis {
    padding: 0 4px;
    color: #606266;
    font-size: 14px;
}
</style>